package com.glodon.paas.document.web.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.service.util.WebService;
import com.glodon.paas.util.BeanFactoryUtil;

public class DocumentBuilder {

    public static void buildUserFile(File file) {
        if (file != null && StringUtils.isNotEmpty(file.getOwnerId())) {
            file.setOwner(getUser(file.getOwnerId()));
        }
    }

    public static void buildUserFiles(List<File> files) {
        if (files != null && files.size() > 0) {
            Set<String> ids = new HashSet<String>();
            for (File file : files) {
                ids.add(file.getOwnerId());
            }
            if (!ids.isEmpty()) {
                Map<String, User> userMap = new HashMap<String, User>();
                if (ids.size() == 1) {
                    String userId = ids.toArray()[0].toString();
                    userMap.put(userId, getUser(userId));
                } else {
                    List<User> users = ((WebService)BeanFactoryUtil.getBean("webService")).getUserByIds(ids);
                    for (User user : users) {
                        userMap.put(user.getId(), user);
                    }
                }
                for (File file : files) {
                    file.setOwner(userMap.get(file.getOwnerId()));
                }
            }
        }
    }

    private static User getUser(String userId) {
        User u = null;
        try {
            if (SecurityUtils.getCurrentUser().getId().equals(userId)) {
                u = SecurityUtils.getCurrentUser();
            }
        } catch (Exception e) {
        }
        if (u == null) {
            u = ((WebService)BeanFactoryUtil.getBean("webService")).getUser(userId);
        }
        return u;
    }
}
